#!/bin/sh

if [ $# != 3 ]; then
    echo "Usage: $0 <master_ip> <path_to_bind_chroot> <slave_name>"
    exit 1
fi

MASTERIP=$1
BINDCHROOT=$2
SLAVE_NAME=$3


#1.init sync&cron enviroment 
#===========================
rm -rf /home/xdslave
userdel xdslave
useradd xdslave -g named -s /sbin/nologin -d /home/xdslave
rm -rf /home/xdslave
mkdir -p /home/xdslave/{.ssh,prog}
mkdir -p /home/xdslave/named/{log,etc/{acl,view,dynamic}}

touch /home/xdslave/.ssh/known_hosts
ssh-keygen -t dsa -f /home/xdslave/rsync-key -N ""

echo "xdreg slave -m $MASTERIP -s $SLAVE_NAME"
xdreg slave -m $MASTERIP -s $SLAVE_NAME
if [ $? -ne 0 ]; then
exit 1
fi

rsync -avz -e 'ssh -i /home/xdslave/rsync-key' xbaydns@$MASTERIP:/home/xbaydns/slave/prog /home/xdslave
rsync -avz -e 'ssh -i /home/xdslave/rsync-key' xbaydns@$MASTERIP:/home/xbaydns/slave/slave.conf /home/xdslave/slave.conf



crontab -u xdslave -l >/home/xdslave/old_crontab 2>/dev/null
crontab -u xdslave /home/xdslave/prog/crontab

crontab -u root -l |grep -v UpdateNamed>/tmp/root_crontab 2>/dev/null
echo "*/5 * * * * /home/xdslave/prog/UpdateNamed.sh">>/tmp/root_crontab
crontab -u root /tmp/root_crontab


#2.prepare bind's chroot
#-----------------------
mkdir -p $BINDCHROOT/{etc/{acl,view,dynamic},dev,var/{run,dump,stats,log}}
touch $BINDCHROOT/var/log/named.log
touch $BINDCHROOT/var/log/query.log

rm $BINDCHROOT/dev/{random,zero,null}
mknod $BINDCHROOT/dev/random c 1 8
mknod $BINDCHROOT/dev/zero c 1 5
mknod $BINDCHROOT/dev/null c 1 3


#3.set envionment variables
#==========================
echo "\
XBAYDNS_CHROOT_PATH=$BINDCHROOT
XBAYDNS_BIND_CONF=/etc
XBAYDNS_BIND_START=/usr/local/sbin/named
XBAYDNS_BIND_USER=named
export PATH XBAYDNS_CHROOT_PATH XBAYDNS_BIND_CONF XBAYDNS_BIND_START XBAYDNS_BIND_USER
"|tee /home/xdslave/xdenv

chmod +x /home/xdslave/xdenv
source /home/xdslave/xdenv
id named || useradd named -s /sbin/nologin
xdinitbind slave $MASTERIP

rm -f /etc/rndc.key
ln -s $BINDCHROOT/etc/rndc.key /etc/
chown -R named:named $BINDCHROOT
chmod -R 770 $BINDCHROOT
chown -R xdslave:named /home/xdslave
chmod -R 700 /home/xdslave
echo "\

----------------------------- Welcome to XBayDNS ---------------------------
"
